function hfile = vmr_SetConvention(hfile, cnv)
% VMR::SetConvention  - set radiological/neurological convention
%
% FORMAT:       [vmr = ] vmr.SetConvention(cnv)
%
% Input fields:
%
%       cnv         either 0 / 'n' for neurological
%                   or 1 / 'r' for radiological convention
%
% Output fields:
%
%       vmr         (possibly) altered object with desired convention
%
% Note: the VMR *must* be in sagittal orientation

% Version:  v0.7b
% Build:    7090216
% Date:     Sep-02 2006, 4:49 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'vmr') || ...
    numel(cnv) ~= 1 || ...
   ((~isa(cnv, 'double') || ...
     ~any([0, 1] == cnv)) && ...
    (~ischar(cnv) || ...
     ~any('nr' == cnv)))
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to ''%s''.', ...
        mfilename ...
    );
end
sbc = bvqxfile_getscont(hfile.L);
bc = sbc.C;

% what target convention
if ischar(cnv)
    cnv = find('nr' == cnv) - 1;
end

% same as current convention
if cnv == bc.Convention
    
    % do nothing
    return;
end

% swap data
bc.VMRData = bc.VMRData(:, :, end:-1:1);
if ~isempty(bc.VMRData16) && ...
    numel(size(bc.VMRData16)) == numel(size(bc.VMRData)) && ...
    all(size(bc.VMRData16) == size(bc.VMRData))
    bc.VMRData16 = bc.VMRData16(:, :, end:-1:1);
end

% patch offset
bc.OffsetX = bc.FramingCube - ...
    (bc.OffsetX + size(bc.VMRData, 1));

% set convention
bc.Convention = cnv;

% add to transformations
t = bc.Trf;
if cnv == 0
    t(end+1).NameOfSpatialTransformation = ...
        'Changing from Radiological to Neurological convention';
else
    t(end+1).NameOfSpatialTransformation = ...
        'Changing from Neurological to Radiological convention';
end
t(end).TypeOfSpatialTransformation = 2;
t(end).SourceFileOfSpatialTransformation = sbc.F;
t(end).NrOfSpatialTransformationValues = 16;
t(end).TransformationValues = diag([1, 1, -1, 1]);
bc.Trf = t;
bc.NrOfPastSpatialTransformations = numel(t);
bvqxfile_setcont(hfile.L, bc);
